/*
 * update_assistant.cpp
 *
 *  Created on: 2022年5月5日
 *      Author: pengzc
 */

#include "grow_server.h"
#include <http/http_client.h>
#include <json/json.h>
#include <utils/Log.h>
#include <thread>

inline int getInt(const Json::Value& obj, const std::string& key,
    int def) {
  if (!obj.isObject()) {
    return def;
  }
  if (!obj.isMember(key)) {
    return def;
  }
  if (!obj[key].isIntegral()) {
    return def;
  }
  return obj[key].asInt();
}

inline std::string getString(const Json::Value& obj, const std::string& key,
    const std::string& def) {
  if (!obj.isObject()){
    return def;
  }
  if (!obj.isMember(key)){
    return def;
  }
  if (!obj[key].isString()) {
    return def;
  }
  return obj[key].asString();
}

VersionInformation GrowServer::latestVersion(
    const std::string& app_name) {
  http::HTTPClient client;
  client.setTimeout(6000);
  client.setConnectTimeout(4000);

  http::HTTPRequest req("GET", "http://grow.flythings.cn/latest/" + app_name);
  auto response = client.perform(req);
  if (response.status() != 200) {
    throw std::runtime_error("参数错误");
  }

  Json::Reader reader;
  Json::Value obj;
  if (!reader.parse(response.body(), obj)) {
    throw std::runtime_error("invalid JSON");
  }
  if (getInt(obj, "errorCode", -1) != 0) {
    throw std::runtime_error("query error");
  }
  VersionInformation info;
  info.version = getString(obj, "version", "");
  info.url = getString(obj, "downloadUrl", "");
  info.file_size = getInt(obj, "fileSize", 0);
  info.is_newer = false;
  LOGD("get new version:%s",info.version.c_str());
  return info;
}

GrowServer::~GrowServer() {
  // TODO 自动生成的析构函数存根
}

